// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import store from './store/store.js'
import * as types from './store/types.js'
import Vuex from 'vuex'
import qs from 'qs'
import axios from 'axios'
import Http from './http.js'
import wx from 'weixin-js-sdk'
import base from './assets/js/base.js'
import 'es6-promise/auto'

Vue.config.productionTip = false;
Vue.prototype.$store = store;
Vue.use(base);

import './assets/common/common.css';
import FastClick from 'fastclick'
if ('addEventListener' in document) {
    document.addEventListener('DOMContentLoaded', function() {
        FastClick.attach(document.body);
    }, false);
}

Vue.use(Vuex)
Vue.use(VueRouter)

//jsonp
import VueJsonp from 'vue-jsonp'
Vue.use(VueJsonp)

//js-md5
import md5 from 'js-md5';
Vue.prototype.$md5 = md5;

//分享
import Share from 'vue-social-share'
import 'vue-social-share/dist/client.css';
Vue.use(Share)

//图片加载
var loadingImg = window.localStorage.getItem("loading")
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
    error: loadingImg,
    loading: loadingImg,
    // loading: require('./assets/img/60x60.png'),
    attempt: 1
})

//图片放大
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'
Vue.use(preview)

axios.defaults.baseURL = 'http://gzh.lamezhimall.com/api';
// axios.defaults.baseURL = 'http://'+ window.location.host + '/api';
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';    
axios.defaults.headers.common['token'] = store.state.token;

    

/*顶部滑动导航*/
import LyTab from 'ly-tab'
Vue.use(LyTab)

/*mint-ui按需引入*/
import { Toast, MessageBox } from 'mint-ui'
Vue.component(Toast.name, Toast)
Vue.component(MessageBox.name, MessageBox)

/*element-ui按需引入*/
import { Button, Select, Progress } from 'element-ui';
Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
Vue.component(Progress.name, Progress);

//复制到剪切板
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)

/*轮播图*/
import VueAwesomeSwiper from 'vue-awesome-swiper'
 
// require styles
import 'swiper/dist/css/swiper.css'

Vue.use(VueAwesomeSwiper, /* { default global options } */)

// 视频播放*/
import VideoPlayer from 'vue-video-player'
Vue.use(VideoPlayer);

// 第一个是videoJs的样式，后一个是vue-video-player的样式，因为考虑到我其他业务组件可能也会用到视频播放
require('video.js/dist/video-js.css')
require('vue-video-player/src/custom-theme.css')

import routes from './router/index.js'
const router = new VueRouter({
    base: '/wx_web',
    linkActiveClass: 'active',
    routes: routes,
    mode: 'history',
    scrollBehavior (to, from, savedPosition) {
        //savedPosition
        if (savedPosition) { //如果savedPosition存在，滚动条会自动跳到记录的值的地方
            return savedPosition
        } else {
            return { x: 0, y: 0 }
        }
    }
});

/*全局引用loading*/
import Loading from './components/loading'
let help = new Vue({
  el: '#help',
  data: {
    showLoading: false
  },
  components: {
    'loading': Loading
  }
})

import CryptoJS from 'crypto-js';
var version = '1.1.1';
var device = 'weixin';
// var cloud_id = window.location.host;
var cloud_id = 'gzh.lamezhimall.com';
var sign_key = focus[47];
var token = store.state.token;
var encrypt = 2;
// var new_key = md5(md5(sign_key).substring(0, 16));
var client = 'weixin'
var wx_login = window.localStorage.getItem("wx_login")
// http request 拦截器
axios.interceptors.request.use(
    config => { 
        help.showLoading = true 
        if (store.state.token) {
            config.headers.token = store.state.token;    
        }
        var time =  Date.parse( new Date())/1000;
        var custom = Math.random().toString(36).substr(2);
        var c = config.url;
        if(c.search("&") != -1){
            var url = '/api/' + c.substring(0, c.indexOf("&"));
        }else{
            var url = '/api/' + c;
        }            
        var str = cloud_id + sign_key +url.toLowerCase() + time + device  + version + token + custom;
        var sign = md5(str);
        config.headers.sign = sign;
        config.headers.cloudid = cloud_id;
        config.headers.time = time;
        config.headers.version = version;
        config.headers.device = device;      
        config.headers.custom = custom;      
        config.headers.encrypt = encrypt; 
        config.headers.client = client; 
        return config;
    },
    err => {
        return Promise.reject(err)
    },
);
// http response 拦截器
axios.interceptors.response.use(
    response => {
        help.showLoading = false;
        var ret = response.data;
        var iv  = CryptoJS.enc.Hex.parse(md5("key_"+ret.time));
        var option = {iv:iv, padding:CryptoJS.pad.ZeroPadding};
        if (ret.encrypt==1 && ret.data){
            var new_key = md5(ret.sign);
            var key = CryptoJS.enc.Hex.parse(new_key);
            var decrypted = CryptoJS.AES.decrypt(ret.data, key, option);
            var string = decrypted.toString(CryptoJS.enc.Utf8);
            try {
                ret.data = JSON.parse(string);
            } catch(e) {
                ret.data = string;
            }
        }
        if (ret.code == 401) {
            store.commit(types.LOGOUT)
      
            // 只有在当前路由不是登录页面才跳转
            if(router.currentRoute.path !== '/auther' && router.currentRoute.path !== '/user' && router.currentRoute.path !== '/'){
                if (wx_login == 1) {
                    router.replace({
                      path: '/auther',
                      query: { redirect: router.currentRoute.path },
                    })
                }else{
                    router.replace({
                      path: '/login',
                      query: { redirect: router.currentRoute.path },
                    })
                }
                
            }  
        }
        return response
    },
    error => {
        if (error.response) {
            switch (error.response.status) {

                case 401:
                    // 401 清除token信息并跳转到登录页面
                    localStorage.removeItem("token");
                    store.commit(types.LOGOUT)
              
                    // 只有在当前路由不是登录页面才跳转
                    if(router.currentRoute.path !== 'login'){
                        router.replace({
                          path: '/login',
                          query: { redirect: router.currentRoute.path },
                        })
                    }
                        
            }
        }
        // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
        return Promise.reject(error.response.data)
    }
);

router.beforeEach((to, from, next) => {
    var appname = window.localStorage.getItem('app_name');
    if (appname) {
       document.title = to.name; 
    }
    
    if (to.meta.requireAuth) {
        if (store.state.token) {
            next();
        }else {
            if (wx_login == 1) {
                next({
                    path: '/auther',
                    query:{redirect:to.fullPath}
                }) 
           }else{
                next({
                    path: '/login',
                    query:{redirect:to.fullPath}
                }) 
           }
            
        }
    }else {
        next();
    }
})

router.afterEach((to,from,next) => {
    window.scrollTo(0,0);
    Promise.resolve()
        .then(() => {
            url: global.location.href
    })
})


/* eslint-disable no-new */
new Vue({
    el: '#app',
    axios,
    router,
    store,
    components: { App },
    template: '<App/>'
})
